/*
 * This program used to setup exe file as an entry to run a specified executable at user login.
 * Author @5mukx
 */

use std::ffi::OsString;
use std::os::windows::ffi::OsStrExt;

use winapi::um::winnt::{KEY_SET_VALUE, REG_SZ};
use winapi::um::winreg::{RegCloseKey, RegOpenKeyExW, RegSetValueExW, HKEY_CURRENT_USER};


fn main() -> std::io::Result<()>{
    let key_path = "Software\\Microsoft\\Windows\\CurrentVersion\\Run";
    let value_name = "Backup";
    let exe_path = r"C:\Temp\backup.exe";

    let wide: Vec<u16> = OsString::from(exe_path).encode_wide().chain(Some(0)).collect();

    unsafe{
        let mut hkey: winapi::shared::minwindef::HKEY = std::ptr::null_mut();
        let res = RegOpenKeyExW(HKEY_CURRENT_USER, 
            key_path.encode_utf16().chain(Some(0)).collect::<Vec<_>>().as_ptr(), 
            0, 
            KEY_SET_VALUE, 
            &mut hkey
        );

        if res == 0{
            let res_set = RegSetValueExW(
                hkey,
                value_name.encode_utf16().chain(Some(0)).collect::<Vec<_>>().as_ptr(),
                0,
                REG_SZ,
                wide.as_ptr() as *const u8,
                ((wide.len() - 1) * 2) as u32,
            );

            if res_set != 0{
                println!("Failed to set registry value.");
            }else{
                println!("Successfully set registry value");
            }

            RegCloseKey(hkey);
        } else{
            println!("Failed to open registry key.");
        }
    }

    Ok(())
}
